<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*-----------------------------------------------------------------------------------------------    
        
    -----------------------------------------------------------------------------------------------*/
class Course_provider_block extends Front_Controller{

    function Course_provider_block(){
        parent::Front_Controller();
    }
    
    function index(){
        $CI =&get_instance();    
		$CI->load->module_model('blocks.course_provider_model');
		$this->url = $CI->course_provider_model->url_prefix.$CI->uri->segment(2);
		$act = $CI->uri->segment(2);
		//$id = (int)($CI->uri->segment(3));
		if($act=='Dang-Ky'){
			$this->register_provider();
		}
		else if($act=='Dang-Nhap'){
			$this->login();
		}
		$this->view(get_class($this));
    }
	
	function register_provider(){
		$CI =&get_instance();
		$CI->load->module_model('blocks.course_provider_model');
		$post = $CI->input->post();
		$this->add('from_action',$this->url);
		$this->add('msg',NULL);		
		
		// validate
		$CI->load->library('form_validation');
		if(!empty($_POST)){
			if ($this->_validate($_POST['course_provider_id']) == FALSE)
			{
				// message
				$this->add('msg', $CI->lang->line('detail_cannot_save')." : ".$CI->form_validation->error_string());
				$this->add('post', $_POST);			
				// go to original page
				//redirect($this->url);
			}
			else{
				$this->saveItem();
			}
		}
		
		$this->view(get_class($this));
		$this->add('fullname', $post?$post['fullname']:'');
		$this->add('login_email', $post?$post['login_email']:'');
		$this->add('password', $post?$post['password']:'');
		$this->add('address', $post?$post['address']:'');
		
		$this->add('link', $post?$post['link']:'');
		
		$this->add('contact_person', $post?$post['contact_person']:'');
		$this->add('email', $post?$post['email']:'');
		$this->add('contact_yahoo', $post?$post['contact_yahoo']:'');
		$this->add('contact_skype', $post?$post['contact_skype']:'');
		$this->add('phone', $post?$post['phone']:'');
		$this->add('primary_phone', $post?$post['primary_phone']:'');
		
		// editor
		$CI->load->library('fckeditor');
		$CI->fckeditor->InstanceName = 'infomation';
		$CI->fckeditor->Value = $post?$post['infomation']:'';
		$CI->fckeditor->SetPathOfFranchise();
		$this->add('infomation', $CI->fckeditor->CreateHtml());
		$this->add('imagepath', '');
	}
	
	function saveItem()
	{
		global $CI;
		// model
		$CI->load->module_model('blocks.course_provider_model');
		
		// save to customers
		$mem_id = $_POST['course_provider_id'];
		if ($CI->course_provider_model->hasCUSTOMERS($mem_id))
		{
			// update
            $data = array(
				CUSTOMERS_LOGIN_EMAIL=>$CI->input->post('login_email'),
				CUSTOMERS_FULL_NAME=>$CI->input->post('fullname'),
				CUSTOMERS_ADDRESS=>$CI->input->post('address'),
				CUSTOMERS_LINK=>$CI->input->post('link'),
				CUSTOMERS_INFO=>$CI->input->post('infomation'),
				CUSTOMERS_TYPE=>$CI->input->post('type'),
				CUSTOMERS_STATUS=>(isset($_POST['active'])?1:0),
				CUSTOMERS_UPDATE_DATE => now_to_mysql()
			);
			if ($CI->input->post('password')!=''&&$CI->input->post('repassword')!=''&&$CI->input->post('password')==$CI->input->post('password')){
				$data[CUSTOMERS_PW] =  md5($CI->input->post('password'));
			}
			else{
				echo 'Please enter Password.';
			}
			if ($_FILES['imagepath']['tmp_name']){
				$data[CUSTOMERS_IMAGE] =  $_FILES["imagepath"]["name"];			
			}
            $CI->db->where(CUSTOMERS_CUSTOMER_ID, $CI->course_provider_model->item);
			$CI->db->update(CUSTOMERS, $data);
		} else {
			// insert
			$data = array(				
				CUSTOMERS_FULL_NAME=>$CI->input->post('fullname'),
				CUSTOMERS_LOGIN_EMAIL=>$CI->input->post('login_email'),
				CUSTOMERS_ADDRESS=>$CI->input->post('address'),
				CUSTOMERS_LINK=>$CI->input->post('link'),
				CUSTOMERS_INFO=>$CI->input->post('infomation'),
				CUSTOMERS_TYPE=>$CI->input->post('type'),
				CUSTOMERS_STATUS=>(isset($_POST['active'])?1:0),
				CUSTOMERS_UPDATE_DATE => now_to_mysql(),
				CUSTOMERS_DATE => now_to_mysql()
			);
			if ($CI->input->post('password')!=''&&$CI->input->post('repassword')!=''&&$CI->input->post('password')==$CI->input->post('password')){
				$data[CUSTOMERS_PW] =  md5($CI->input->post('password'));		
			}
			if ($_FILES['imagepath']['tmp_name']){
				$data[CUSTOMERS_IMAGE] =  $_FILES["imagepath"]["name"];			
			}
			$CI->db->insert(CUSTOMERS, $data);
		}		
		//upload
		$this->upload();
		
		// message
		$this->add('msg', $CI->lang->line('detail_save'));
		
		// go to original page
		redirect('Trang-Chu');
	}		
	function upload(){
		//upload	
		global $CI;	
		$CI->load->library("fckeditor");
		$path = $CI->fckeditor->UploadPath.'/images';;			
        $path = rtrim($_SERVER['DOCUMENT_ROOT'], "/").$path;
		if ($_FILES['imagepath']['tmp_name'])
		{
			
			$config['upload_path'] = $path;
			$config['allowed_types'] = 'gif|jpg|jpeg|png';
			$config['max_size'] = '2048';
			$config['max_width'] = '1024';
			$config['max_height'] = '768';			
			$config['max_filename'] = '54';
			$CI->load->library('upload', $config);
			if (!$CI->upload->do_upload('imagepath'))
			{
				//$CI->upload->display_errors();
				set_flash_message($CI->upload->display_errors());
			} 
			else{
				$file_name = $CI->upload->file_name;
				$new_width= 132;
				$new_height= 113;
				$uppath = $path."/".$file_name;
				list($width, $height, $type, $attr) = @getimagesize($uppath);
				if($width>0&&$height>0){
					//$new_height = (int)($new_width*$height/$width);
					$new_width = (int)($new_height*$width/$height);
				}

				// create thumbnail
				$CI->load->module_helper('image.create_thumbnail');
				create_thumbnail($path.'/'.$file_name, $path.'/thumb/'.$file_name, $new_width, $new_height);
				
			}
		}
	}
	//validate function
	function _validate($edit_id){
        $CI = & get_instance();
        $CI->load->library('form_validation');
        $CI->load->helper('form');
        $CI->form_validation->set_rules('fullname', 'fullname', 'trim|required');
		$CI->form_validation->set_rules('login_email', 'login_email', 'trim|required|valid_emails');
		if($edit_id){
			if(isset($_POST['repassword'])&&($_POST['repassword'])){
				$CI->form_validation->set_rules('password', 'Password', 'trim|required|callback__validate_pw');
				$CI->form_validation->_callback_object = $this;
			}
		}
		else{
			$CI->form_validation->set_rules('repassword', 'Re-password', 'trim|required');
			$CI->form_validation->set_rules('password', 'Password', 'trim|required|callback__validate_pw');
			$CI->form_validation->_callback_object = $this;
		}
        return $CI->form_validation->run();
    }
	
	function _validate_pw(){
        $CI = & get_instance();
		$CI->load->library('form_validation');
        $CI->load->helper('form');
        if($CI->input->post('repassword')!=$CI->input->post('password')){
            $CI->form_validation->set_message('_validate_pw', lang('_invalid_pw'));
            return FALSE;
        }
        return TRUE;
    }
	function login(){
		$CI = & get_instance();
		$CI->load->module_library('blocks.FrontAuth');
		$email = $CI->input->post('email');
		$pass = $CI->input->post('pass');
		$CI->load->library('form_validation');
        $CI->load->helper('form');
        
        $CI->form_validation->set_rules('email', 'Email', 'trim|required');
		$CI->form_validation->set_rules('pass', 'Password', 'trim|required');

		if ($CI->form_validation->run() !== FALSE){
            $result = $CI->course_provider_model->do_login($email, $pass);
            if($result == 0){
                //$CI->form_validation->set_error('email', 'Email không tồn tại');
				$this->add('message','Email không tồn tại');
            }elseif($result == -1){
                //$CI->form_validation->set_error('pass', 'Mật khẩu sai');
				$this->add('message','Sai Mật Khẩu');
            }else{
                $CI->frontauth->logged($result);
            }
        }
		$this->view('get_blank_block');
	}
	    
    function logout(){
        $CI->load->module_library('blocks.FrontAuth');
        $CI->frontauth->logout();
		$this->view('get_blank_block');
    }

}